<template>
  <div class="app-container" style="height: 100%">
    <el-tabs v-model="queryParams.rdcType" class="tab-box" :class="{ disabled: disableAction }" @tab-click="handleQuery">
      <el-tab-pane label="集团检查" name="DEPT1" v-if="showBtns.jt" />
      <el-tab-pane label="集群检查" name="DEPT2" v-if="showBtns.jq" />
    </el-tabs>
    <el-form ref="queryForm" :model="queryParams" size="mini" inline :class="{ disabled: disableAction }" @submit.native.prevent>
      <el-form-item prop="businessType">
        <el-input v-model.trim="queryParams.businessType" placeholder="请输入检查类型" clearable @keyup.enter.native="handleQuery" style="width: 130px" />
      </el-form-item>
      <el-form-item prop="proName" key="proName">
        <el-input v-model.trim="queryParams.proName" placeholder="请输入检查项目" clearable @keyup.enter.native="handleQuery" style="width: 130px" />
      </el-form-item>
      <el-form-item style="margin-right: 30px">
        <el-button size="mini" type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button size="mini" type="primary" icon="el-icon-plus" @click="openSelectBusinessType" v-if="showBtns.add && showAddBtn">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="listLoading" :data="list" size="small" row-key="pid" default-expand-all height="calc(100% - 150px)">
      <el-table-column label="检查类型" prop="businessType" show-overflow-tooltip min-width="150" />
      <el-table-column label="集群" prop="deptName1" show-overflow-tooltip min-width="100" />
      <el-table-column label="事业部" prop="deptName2" show-overflow-tooltip min-width="100" />
      <el-table-column label="城市公司" prop="deptName3" show-overflow-tooltip min-width="120" />
      <el-table-column label="检查项目" prop="displayName" show-overflow-tooltip min-width="200" />
      <el-table-column label="检查项数量" prop="chkitemNum" align="center" />
      <el-table-column label="创建人" prop="creatorName" />
      <el-table-column label="生成时间" prop="createTime" min-width="140" />
      <el-table-column label="单据状态" align="center" width="80">
        <el-tag slot-scope="{ row }" size="small" :type="row.isEnable ? 'success' : 'info'">{{ row.isEnable ? '正常' : '作废' }}</el-tag>
      </el-table-column>
      <el-table-column label="原因" prop="reason" show-overflow-tooltip min-width="100" />
      <el-table-column label="操作" width="120" fixed="right">
        <template slot-scope="{ row }">
          <el-button size="mini" type="text" class="btn" icon="fa fa-dice" :loading="row.suppDrawLoading" @click="suppDraw(row)" v-if="row.isRecord && row.showSuppDrawBtn && showAddBtn"> 补抽</el-button>
          <el-button size="mini" type="text" icon="el-icon-view" @click="gotoRltChkitem(row)" v-else-if="!row.isRecord && showBtns.proInfo">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" :loading="row.isEnableLoading" @click="toggleIsEnable(row)" v-if="row.showDisableBtn">作废</el-button>
          <el-button size="mini" type="text" icon="el-icon-refresh-left" :loading="row.isEnableLoading" @click="toggleIsEnable(row)" v-else-if="row.showEnableBtn">恢复</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <SelectBusinessType ref="SelectBusinessType" @ok="onSelectBusinessType" />
    <ChkProWizard ref="ChkProWizard" @ok="getList" />
  </div>
</template>
<script>
// 项目检查-检查单据列表
import store from '@/store'
import auth from '@/plugins/auth'
import { CQ_EVAL_RDC_TYPE as RDC_TYPE } from '@/utils/baseData'
import { listBsNode } from '@/api/cqPe/bsNode'
import { listPeRecord, enableRecord, disableRecord, enableRltPro, disableRltPro, getDept1List } from '@/api/cqPe/peRecord'
import SelectBusinessType from './components/SelectBusinessType'
import ChkProWizard from './components/ChkProWizard'
import { rdcTypeAuthMap, firAssToBelongSysMap, handleableGenType } from './components/common'
export default {
  name: 'GcPeRecord',
  components: { SelectBusinessType, ChkProWizard },
  data() {
    return {
      listLoading: false,
      total: 0,
      list: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        rdcType: '',
        businessType: '',
        proName: '',
        belongSystem: ''
      },
      firAss: '', // gc, ds
      dept1Loading: false,
      dept1List: [] // 集群
    }
  },
  computed: {
    disableAction() {
      return this.dept1Loading || this.listLoading
    },
    showBtns() {
      // 操作按钮权限
      const firAss = this.firAss
      const rdcType = rdcTypeAuthMap[this.queryParams.rdcType] || ''
      const permCode = `cqPe:peRecord:${firAss}:${rdcType}`

      const query = auth.hasPermi(`${permCode}:query`)
      const add = auth.hasPermi(`${permCode}:add`)
      const info = auth.hasPermi(`${permCode}:info`)
      const enable = auth.hasPermi(`${permCode}:enable`)
      const disable = auth.hasPermi(`${permCode}:disable`)
      const proInfo = auth.hasPermi(`${permCode}:project:info`)
      const proEnable = auth.hasPermi(`${permCode}:project:enable`)
      const proDisable = auth.hasPermi(`${permCode}:project:disable`)

      const jt = auth.hasPermi(`cqPe:peRecord:${firAss}:jt:query`)
      const jq = auth.hasPermi(`cqPe:peRecord:${firAss}:jq:query`)

      return { query, add, info, enable, disable, proInfo, proEnable, proDisable, jt, jq }
    },
    isJq() {
      // 是否集群
      return this.queryParams.rdcType === RDC_TYPE.DEPT2
    },
    showAddBtn() {
      // 集群检查时，需要有集群数据才能新增
      if (this.isJq) return !!this.dept1List.length
      return true
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      // 根据路由判断一级考核指标(工程/设计)
      const currPath = this.$route.path.split('/').pop()
      let firAss = ''
      if (currPath === 'GcPeRecord') firAss = 'gc'
      else if (currPath === 'dsPeRecord') firAss = 'ds'
      else return

      // 判断检查单位(集团/集群)权限
      const permCode = `cqPe:peRecord:${firAss}`
      const jt = auth.hasPermi(`${permCode}:jt:query`)
      const jq = auth.hasPermi(`${permCode}:jq:query`)
      if (jt && jq) this.queryParams.rdcType = RDC_TYPE.DEPT1
      else if (jt) this.queryParams.rdcType = RDC_TYPE.DEPT1
      else if (jq) this.queryParams.rdcType = RDC_TYPE.DEPT2
      else return

      this.queryParams.belongSystem = firAssToBelongSysMap[firAss]
      this.firAss = firAss
      this.getDept1List()
      this.getList()
    },
    async getDept1List() {
      this.dept1Loading = true
      const res = await getDept1List().catch(() => false)
      this.dept1Loading = false
      if (res === false) return

      const data = res.data || []
      this.dept1List = data
    },
    async getList() {
      const { showBtns } = this
      if (!showBtns.query) return (this.list = [])

      this.listLoading = true
      const res = await listPeRecord(this.queryParams).catch(() => false)
      this.listLoading = false
      if (res === false) return

      const isAdmin = auth.hasRole('admin')
      const userName = store.getters.user?.userName || ''
      // 改为两级树形。一级为单据，二级为项目
      const data = res.rows || []
      data.map(i => {
        i.isRecord = true
        i.pid = i.peRecordId
        i.isEnableLoading = false
        i.suppDrawLoading = false

        const isOwn = isAdmin || !userName || !i.creator ? 1 : userName === i.creator
        // 补抽按钮（有新增权，是拥有者，本项启用，检查/抽查）
        i.showSuppDrawBtn = showBtns.add && isOwn && i.isEnable && handleableGenType.includes(i.generationType)
        // 作废按钮（有单据作废权，是拥有者，本项启用）
        i.showDisableBtn = showBtns.disable && isOwn && i.isEnable
        // 恢复按钮（有单据恢复权，是拥有者，本项作废）
        i.showEnableBtn = showBtns.enable && isOwn && !i.isEnable

        i.children = i.cqPeRltPro || []
        i.children.map(r => {
          r.pid = r.rltProId
          r.isEnableLoading = false

          const isOwn = isAdmin || !userName || !r.creator ? 1 : userName === r.creator
          // 作废按钮（有项目作废权，是拥有者，单据启用，本项启用）
          r.showDisableBtn = showBtns.proDisable && isOwn && i.isEnable && r.isEnable
          // 恢复按钮（有项目恢复权，是拥有者，单据启用，本项作废）
          r.showEnableBtn = showBtns.proEnable && isOwn && i.isEnable && !r.isEnable
        })
      })
      this.list = data
      this.total = res.total || 0
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      // 注：部分字段重置
      this.queryParams.pageSize = 10
      this.queryParams.businessType = ''
      this.queryParams.proName = ''
      this.handleQuery()
    },
    async toggleIsEnable(item) {
      // 单据/项目 的 启用/禁用
      const { isRecord } = item
      if (item.isEnableLoading) return
      const isEnable = item.isEnable ? 0 : 1
      const name = isEnable === 1 ? '启用' : '作废'

      const res1 = await this.$prompt('', `${name}原因`, {
        inputPlaceholder: `请输入${name}原因`,
        inputValidator: val => !!(val || '').trim(),
        inputErrorMessage: `请输入${name}原因`
      }).catch(action => ({ action }))
      if (res1.action !== 'confirm') return

      const reason = (res1.value || '').trim()
      const opt = isRecord ? { peRecordId: item.peRecordId, isEnable, reason } : { rltProId: item.rltProId, isEnable, reason }
      const submitApi = isRecord ? (isEnable ? enableRecord : disableRecord) : isEnable ? enableRltPro : disableRltPro
      item.isEnableLoading = true
      const res = await submitApi(opt).catch(() => false)
      item.isEnableLoading = false
      if (res === false) return

      this.$message.success(`已${name}`)
      this.getList()
    },
    gotoRltChkitem(item) {
      const deptName = [item.deptName1, item.deptName2, item.deptName3, item.curProName].filter(i => i).join(' - ')
      const query = {
        firAss: this.firAss,
        rdcType: this.queryParams.rdcType,
        proIsEnable: item.isEnable,
        deptName
      }
      this.$router.push({ path: `/cqPe/peRltChkitem/${item.rltProId}`, query })
    },
    openSelectBusinessType() {
      const { rdcType, belongSystem } = this.queryParams
      this.$refs.SelectBusinessType.open({ rdcType, belongSystem })
    },
    onSelectBusinessType(data) {
      // data 包含 bsNode 所有字段，外加 deptId1
      const opt = {
        ...data,
        dept1List: this.dept1List,
        firAss: this.firAss
      }
      this.$refs.ChkProWizard.init(opt)
    },
    async suppDraw(item) {
      // 补抽 (supplementary draw)
      // const { deptId1, bsNodeId, rdcType, belongSystem, businessType } = item
      const { peRecordId, bsNodeId, businessType } = item
      // 从第一个子级取，补抽不可更改集群
      const deptId1 = item.deptId1 || item.children[0].deptId1 || ''

      if (!bsNodeId) return this.msgError('数据有误，检查节点ID"bsNodeId"不能为空')
      if (this.isJq && !deptId1) return this.msgError('数据有误，集群ID"deptId1"不能为空')

      // 无 generationType，通过 bsNodeId 取完整的该节点配置信息
      const opt = { bsNodeId, pageSize: 1, isEnable: true }
      item.suppDrawLoading = true
      const loading = this.$loading({ lock: true, text: '获取节点配置', background: 'rgba(255, 255, 255, 0.2)' })
      const res = await listBsNode(opt).catch(() => false)
      loading.close()
      item.suppDrawLoading = false
      if (res === false) return

      const data = res.rows?.[0] || {}
      if (!data.bsNodeId) return this.msgError(`找不到“${businessType}”的节点配置`)

      const opt2 = {
        ...data,
        deptId1,
        dept1List: this.dept1List,
        firAss: this.firAss,
        peRecordId
      }
      this.$refs.ChkProWizard.init(opt2)
    }
  }
}
</script>
<style lang="scss" scoped>
.tab-box {
  /deep/ .el-tabs__item {
    font-size: 12px;
  }
}
.btn /deep/ .fa {
  font-size: inherit;
}
</style>
